using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TerritoryGame.Infrastructure.Persistence;

namespace TerritoryGame.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class HealthController : ControllerBase
{
    private readonly GameDbContext _context;
    
    public HealthController(GameDbContext context)
    {
        _context = context;
    }
    
    [HttpGet]
    public async Task<ActionResult<HealthStatus>> GetHealth()
    {
        try
        {
            // 检查数据库连接
            await _context.Database.CanConnectAsync();
            
            // 获取基本统计信息
            var roomCount = await _context.GameRooms.CountAsync();
            var gameCount = await _context.Games.CountAsync();
            var activeGames = await _context.Games
                .Where(g => g.Room.Status == Domain.Entities.GameStatus.Playing)
                .CountAsync();
            
            var status = new HealthStatus
            {
                Status = "Healthy",
                Timestamp = DateTime.UtcNow,
                Version = "1.0.0",
                Database = "Connected",
                Statistics = new HealthStatistics
                {
                    TotalRooms = roomCount,
                    TotalGames = gameCount,
                    ActiveGames = activeGames
                }
            };
            
            return Ok(status);
        }
        catch (Exception ex)
        {
            var status = new HealthStatus
            {
                Status = "Unhealthy",
                Timestamp = DateTime.UtcNow,
                Version = "1.0.0",
                Database = $"Error: {ex.Message}"
            };
            
            return Ok(status);
        }
    }
}

public record HealthStatus
{
    public string Status { get; init; } = string.Empty;
    public DateTime Timestamp { get; init; }
    public string Version { get; init; } = string.Empty;
    public string Database { get; init; } = string.Empty;
    public HealthStatistics? Statistics { get; init; }
}

public record HealthStatistics
{
    public int TotalRooms { get; init; }
    public int TotalGames { get; init; }
    public int ActiveGames { get; init; }
}
